package com.qingcheng.consumer;

import com.alibaba.fastjson.JSON;
import com.qingcheng.dao.OrderMapper;
import com.qingcheng.pojo.order.Order;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.service.order.WxPayService;
import com.qingcheng.service.pay.WeixinPayService;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Map;

public class WxPayMessageConsumer implements MessageListener {

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderService orderService;

    @Override
    public void onMessage(Message message) {
        String jsonString = new String(message.getBody());
        String orderId = JSON.parseObject(jsonString, String.class);
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if ("0".equals(order.getPayStatus())) {
            Map map = wxPayService.queryPayStatus(orderId);
            if (map.get("return_code").equals("SUCCESS") && map.get("result_code").equals("SUCCESS")) {
                order.setId(orderId);
                order.setUpdateTime(new Date());
                order.setPayStatus("1");
                orderMapper.updateByPrimaryKeySelective(order);
            } else {
                orderService.closeOrder(orderId);
            }
        }
    }
}
